package com.gitee.cashzhang27.test.boot.other.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

/**
 * @author cash Zhang
 * @since 2018/12/12 16:27
 */
public class PoiUtils {

  private static final String DEST_FILE_SUFFIX = ".html";
  private static final String WORD_2007_REPLCAE = "<div style=\"width:595.0pt;margin-bottom:72.0pt;margin-top:72.0pt;margin-left:90.0pt;margin-right:90.0pt;\">";

  public static String wordToHtml(String srcFilePath, String fileName, String destFilePath)
      throws IOException, TransformerException, ParserConfigurationException {
    File srcFile = new File(srcFilePath);
    if (!srcFile.exists()) {
      throw new IOException("Sorry File does not Exists!");
    } else {
      if (srcFile.getName().endsWith(".docx") || srcFile.getName().endsWith(".DOCX")) {
        return word2007ToHtml(srcFilePath, fileName, destFilePath);
      } else {
        return word2003ToHtml(srcFilePath, fileName, destFilePath);
      }
    }
  }


  /**
   * 2007版本word转换成html
   */
  private static String word2007ToHtml(String srcFilePath, String fileName, String destFilePath)
      throws IOException {
    // 1) 加载word文档生成 XWPFDocument对象
    InputStream in = new FileInputStream(new File(srcFilePath));
    XWPFDocument document = new XWPFDocument(in);

    // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
    String imageFolderFileName = destFilePath + File.separator + fileName;
    File imageFolderFile = new File(imageFolderFileName);
    // 加载HTML页面时图片路径
    XHTMLOptions options = XHTMLOptions.create()
        .URIResolver(new FileURIResolver(imageFolderFile));
    // 图片保存文件夹路径
    options.setExtractor(new FileImageExtractor(imageFolderFile));
    options.setIgnoreStylesIfUnused(false);
    options.setFragment(true);

    // 3) 将 XWPFDocument转换成XHTML
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    XHTMLConverter.getInstance().convert(document, outStream, options);
    String content = new String(outStream.toByteArray()).replace(WORD_2007_REPLCAE, "<div >");
    outStream.close();
    File htmlFile = new File(destFilePath, fileName + DEST_FILE_SUFFIX);
    FileUtils.writeStringToFile(htmlFile, content,
        "utf-8");
    return htmlFile.getPath();
  }

  /**
   * 2003版本word转换成html
   */
  private static String word2003ToHtml(String srcFilePath, String fileName, String destFilePath)
      throws IOException, TransformerException, ParserConfigurationException {
    InputStream input = new FileInputStream(new File(srcFilePath));
    HWPFDocument wordDocument = new HWPFDocument(input);
    WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
        DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
    //设置图片存放的位置
    wordToHtmlConverter.setPicturesManager(new PicturesManager() {
      @Override
      public String savePicture(byte[] content, PictureType pictureType, String suggestedName,
          float widthInches, float heightInches) {
        String imgPath =
            destFilePath + File.separator + fileName + File.separator;
        File file = new File(imgPath + suggestedName);
        if (!file.getParentFile().exists()){
          file.getParentFile().mkdirs();
        }
        try {
          OutputStream os = new FileOutputStream(file);
          os.write(content);
          os.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        return imgPath + suggestedName;
      }
    });

    //解析word文档
    wordToHtmlConverter.processDocument(wordDocument);
    Document htmlDocument = wordToHtmlConverter.getDocument();

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    DOMSource domSource = new DOMSource(htmlDocument);
    StreamResult streamResult = new StreamResult(outStream);

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer serializer = factory.newTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.METHOD, "html");

    serializer.transform(domSource, streamResult);

    outStream.close();
    String content = new String(outStream.toByteArray());
    File htmlFile = new File(destFilePath, fileName + DEST_FILE_SUFFIX);
    FileUtils.writeStringToFile(htmlFile, content,
        "utf-8");
    return htmlFile.getPath();
  }
}
